import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  SafeAreaView,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { useTranslation } from 'react-i18next';
import Toast from 'react-native-simple-toast';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons';
import appleAuth, { AppleButton } from '@invertase/react-native-apple-authentication';

import theme from '../../utils/theme';
import { loginApi as AuthAPI } from '../../http/api.js';
import StorageUtil from '../../utils/StorageUtil';
import { useDispatch } from 'redux-react-hook';
import CryptoJS from 'crypto-js';
const LoginView = ({ navigation }) => {
  const { t, i18n } = useTranslation();
  
  // 添加调试信息
  console.log('i18n ready:', i18n.isInitialized);
  console.log('current language:', i18n.language);
  console.log('test translation:', t('login.slogan'));
  const dispatch = useDispatch();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  // 邮箱验证
  const validateEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  // 邮件登录处理
  const handleLogin = async () => {
    if (!email.trim()) {
      Toast.show(t('login.emailRequired'), Toast.SHORT);
      return;
    }

    if (!validateEmail(email)) {
      Toast.show(t('login.emailInvalid'), Toast.SHORT);
      return;
    }

    if (!password.trim()) {
      Toast.show(t('login.passwordRequired'), Toast.SHORT);
      return;
    }

    if (password.length < 6) {
      Toast.show(t('login.passwordTooShort'), Toast.SHORT);
      return;
    }

    setIsLoading(true);
    try {
      // 调用统一登录API - 邮件登录
      const result = await AuthAPI({
        type: 'email',
        email,
        password: CryptoJS.SHA256(password).toString()
      });
      
      if (result.code === 200) {
        // 登录成功
        const { token, user } = result.data;
        
        // 保存token到本地存储
        await StorageUtil.setItem('user_token', token);
        
        // 更新Redux状态
        dispatch({
          type: 'SET_LOGIN',
          isLogin: true
        });
        Toast.show(t('login.success'), Toast.SHORT);
      } else {
        Toast.show(result.message || t('login.failed'), Toast.SHORT);
      }
      
    } catch (error) {
      console.error('Login error:', error);
      Toast.show(error.message || t('login.failed'), Toast.SHORT);
    } finally {
      setIsLoading(false);
    }
  };

  // 忘记密码
  const handleForgotPassword = () => {
    if (navigation.push) {
      navigation.push('ForgotPasswordView');
    } else {
      Toast.show(t('login.forgotPassword'), Toast.SHORT);
    }
  };

  // 注册
  const handleRegister = () => {
    if (navigation.push) {
      navigation.push('RegisterView');
    } else {
      Toast.show(t('login.register'), Toast.SHORT);
    }
  };

  // Apple登录处理
  const handleAppleLogin = async () => {
    try {
      setIsLoading(true);
      
      // 执行Apple登录请求
      const appleAuthRequestResponse = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
      });

      // 获取用户认证状态
      const credentialState = await appleAuth.getCredentialStateForUser(appleAuthRequestResponse.user);

      // 确保用户已认证
      if (credentialState === appleAuth.State.AUTHORIZED) {
        const { identityToken, user: appleUserId, email: appleEmail } = appleAuthRequestResponse;
        
        // 调用统一登录API - Apple登录
        const result = await AuthAPI.login({
          type: 'apple',
          apple_user_id: appleUserId,
          identity_token: identityToken,
          email: appleEmail || '', // 确保传递email字段
          // 可选的额外数据
          avatar: '',
          latitude: 0.0,
          longitude: 0.0
        });
        
        if (result.code === 200) {
          // Apple登录成功
          const { token, user } = result.data;
          
          // 保存token到本地存储
          await StorageUtil.setItem('user_token', token);
          
          // 更新Redux状态
          dispatch({
            type: 'SET_LOGIN',
            isLogin: true,
            user: user
          });
          Toast.show(t('login.appleLoginSuccess'), Toast.SHORT);
        } else {
          Toast.show(result.message || t('login.appleLoginFailed'), Toast.SHORT);
        }
      } else {
        Toast.show(t('login.appleAuthFailed'), Toast.SHORT);
      }
      
    } catch (error) {
      console.error('Apple login error:', error);
      
      // 处理特定的Apple登录错误
      if (error.code === appleAuth.Error.CANCELED) {
        Toast.show(t('login.appleLoginCanceled'), Toast.SHORT);
      } else if (error.code === appleAuth.Error.FAILED) {
        Toast.show(t('login.appleLoginFailed'), Toast.SHORT);
      } else if (error.code === appleAuth.Error.INVALID_RESPONSE) {
        Toast.show(t('login.appleInvalidResponse'), Toast.SHORT);
      } else if (error.code === appleAuth.Error.NOT_HANDLED) {
        Toast.show(t('login.appleNotHandled'), Toast.SHORT);
      } else if (error.code === appleAuth.Error.UNKNOWN) {
        Toast.show(t('login.appleUnknownError'), Toast.SHORT);
      } else {
        Toast.show(error.message || t('login.appleLoginFailed'), Toast.SHORT);
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <KeyboardAvoidingView 
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoid}
      >
        <View style={styles.content}>
          {/* Logo区域 */}
          <View style={styles.logoContainer}>
            <View style={styles.logoCircle}>
              <Text style={styles.logoText}>📍</Text>
            </View>
            <Text style={styles.appName}>FindApp</Text>
            <Text style={styles.appSlogan}>{t('login.slogan')}</Text>
          </View>

          {/* 登录表单 */}
          <View style={styles.formContainer}>
            {/* 邮箱输入 */}
            <View style={styles.inputContainer}>
              <TextInput
                style={styles.textInput}
                placeholder={t('login.emailPlaceholder')}
                placeholderTextColor={theme.colors.text.hint}
                value={email}
                onChangeText={setEmail}
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
                editable={!isLoading}
              />
            </View>

            {/* 密码输入 */}
            <View style={styles.inputContainer}>
              <View style={styles.passwordContainer}>
                <TextInput
                  style={[styles.textInput, styles.passwordInput]}
                  placeholder={t('login.passwordPlaceholder')}
                  placeholderTextColor={theme.colors.text.hint}
                  value={password}
                  onChangeText={setPassword}
                  secureTextEntry={!showPassword}
                  autoCapitalize="none"
                  autoCorrect={false}
                  editable={!isLoading}
                />
                <TouchableOpacity 
                  style={styles.eyeButton}
                  onPress={() => setShowPassword(!showPassword)}
                  disabled={isLoading}
                >
                  <FontAwesomeIcon 
                    icon={showPassword ? faEye : faEyeSlash} 
                    size={18} 
                    color={theme.colors.text.secondary}
                  />
                </TouchableOpacity>
              </View>
            </View>

            {/* 忘记密码 */}
            <TouchableOpacity 
              style={styles.forgotPasswordButton}
              onPress={handleForgotPassword}
              disabled={isLoading}
            >
              <Text style={styles.forgotPasswordText}>{t('login.forgotPassword')}</Text>
            </TouchableOpacity>

            {/* 登录按钮 */}
            <TouchableOpacity 
              style={[styles.loginButton, isLoading && styles.loginButtonDisabled]}
              onPress={handleLogin}
              disabled={isLoading}
            >
              <Text style={styles.loginButtonText}>
                {isLoading ? t('login.loggingIn') : t('login.login')}
              </Text>
            </TouchableOpacity>

            {/* 注册链接 */}
            <View style={styles.registerContainer}>
              <Text style={styles.registerPrompt}>{t('login.noAccount')}</Text>
              <TouchableOpacity onPress={handleRegister} disabled={isLoading}>
                <Text style={styles.registerLink}>{t('login.register')}</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>

        {/* 第三方登录 - 固定在底部 */}
        <View style={styles.bottomContainer}>
          {/* 分割线 */}
          <View style={styles.dividerContainer}>
            <View style={styles.dividerLine} />
            <Text style={styles.dividerText}>{t('login.or')}</Text>
            <View style={styles.dividerLine} />
          </View>

          {/* Apple登录 */}
          <AppleButton
            buttonStyle={AppleButton.Style.BLACK}
            buttonType={AppleButton.Type.SIGN_IN}
            style={[styles.appleButton, isLoading && styles.appleButtonDisabled]}
            onPress={handleAppleLogin}
            disabled={isLoading}
          />
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background.primary,
  },
  keyboardAvoid: {
    flex: 1,
  },
  content: {
    flex: 1,
    paddingHorizontal: theme.spacing.lg,
  },
  
  // Logo样式
  logoContainer: {
    alignItems: 'center',
    paddingTop: theme.spacing.xxl,
    paddingBottom: theme.spacing.xl,
  },
  logoCircle: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: theme.colors.primary.main,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: theme.spacing.md,
    ...theme.shadows.md,
  },
  logoText: {
    fontSize: 40,
  },
  appName: {
    ...theme.typography.heading.h2,
    color: theme.colors.text.primary,
    marginBottom: theme.spacing.xs,
  },
  appSlogan: {
    ...theme.typography.body.medium,
    color: theme.colors.text.secondary,
    textAlign: 'center',
  },
  
  // 表单样式
  formContainer: {
    flex: 1,
  },
  
  // 输入框样式
  inputContainer: {
    marginBottom: theme.spacing.md,
  },
  textInput: {
    ...theme.typography.body.large,
    backgroundColor: theme.colors.background.secondary,
    borderWidth: 1,
    borderColor: theme.colors.border.light,
    borderRadius: theme.borderRadius.md,
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.sm,
    color: theme.colors.text.primary,
    minHeight: 48,
    textAlignVertical: 'center',
  },
  passwordContainer: {
    position: 'relative',
  },
  passwordInput: {
    paddingRight: 50,
  },
  eyeButton: {
    position: 'absolute',
    right: theme.spacing.md,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    width: 30,
  },
  eyeIcon: {
    fontSize: 18,
  },
  
  // 忘记密码
  forgotPasswordButton: {
    alignSelf: 'flex-end',
    marginBottom: theme.spacing.lg,
  },
  forgotPasswordText: {
    ...theme.typography.body.small,
    color: theme.colors.primary.main,
  },
  
  // 登录按钮
  loginButton: {
    backgroundColor: theme.colors.primary.main,
    borderRadius: theme.borderRadius.md,
    paddingVertical: theme.spacing.md,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: theme.spacing.lg,
    ...theme.shadows.sm,
  },
  loginButtonDisabled: {
    backgroundColor: theme.colors.neutral.gray[400],
  },
  loginButtonText: {
    ...theme.typography.button.large,
    color: theme.colors.primary.contrast,
  },
  
  // 注册链接
  registerContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  registerPrompt: {
    ...theme.typography.body.medium,
    color: theme.colors.text.secondary,
    marginRight: theme.spacing.xs,
  },
  registerLink: {
    ...theme.typography.body.medium,
    color: theme.colors.primary.main,
    fontWeight: '500',
  },

  // 底部容器
  bottomContainer: {
    paddingHorizontal: theme.spacing.lg,
    paddingBottom: theme.spacing.lg,
  },
  
  // 分割线
  dividerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: theme.spacing.md,
  },
  dividerLine: {
    flex: 1,
    height: 1,
    backgroundColor: theme.colors.border.light,
  },
  dividerText: {
    ...theme.typography.body.small,
    color: theme.colors.text.secondary,
    marginHorizontal: theme.spacing.md,
  },
  
  // Apple登录按钮
  appleButton: {
    width: '100%',
    height: 50,
  },
  appleButtonDisabled: {
    opacity: 0.6,
  },
  appleLoginButton: {
    backgroundColor: '#000000',
    borderRadius: theme.borderRadius.md,
    paddingVertical: theme.spacing.md,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    ...theme.shadows.sm,
  },
  appleIcon: {
    fontSize: 20,
    marginRight: theme.spacing.sm,
  },
  appleLoginText: {
    ...theme.typography.button.medium,
    color: '#FFFFFF',
    fontWeight: '600',
  },
});

export default LoginView;